package com.huixue.cn.ztej.api.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.TGradeInfo;
import com.huixue.cn.ztej.bean.TQuestionsInfo;
import com.huixue.cn.ztej.bean.TSchoolInfo;
import com.huixue.cn.ztej.bean.TTudentInfo;
import com.huixue.cn.ztej.constants.ResourceLocator;
import com.huixue.cn.ztej.controller.BaseController;
import com.huixue.cn.ztej.controller.TStudentController;
import com.huixue.cn.ztej.service.SysProjectService;
import com.huixue.cn.ztej.service.SysSectionService;
import com.huixue.cn.ztej.service.SysUserService;
import com.huixue.cn.ztej.service.TGradeService;
import com.huixue.cn.ztej.service.TQuestionsService;
import com.huixue.cn.ztej.service.TSchoolService;
import com.huixue.cn.ztej.service.TTudentService;
import com.huixue.cn.ztej.utils.DateUtil;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.framwork.JacksonUtil;


@Controller
@RequestMapping(value = "/api/user")
public class ApiUserController  extends BaseController {

	@Autowired(required = true)
	SysUserService sysUserService;
	
	@Autowired(required = true)
	SysProjectService sysProjectService;
	
	@Autowired(required = true)
	SysSectionService sysSectionService;
	
	@Autowired(required = true)
	private  TSchoolService tSchoolService;
	
	@Autowired(required = true)
	private TGradeService tGradeService;
	
	@Autowired
	private CommonsMultipartResolver multipartResolver;
	
	@Autowired(required = true)
	private TTudentService sTudentService;
	
	@Autowired(required = true)
	private TQuestionsService tQuestionsService;
	
	/*@RequestMapping(value = "/reg")
	public String registerBefore(HttpServletRequest request,HttpServletResponse response,Model model) {
		try{
			OAuthInfo aouAuthInfo  = WeixinHelper.getUserOpenId(request);
			User currentUser = sysUserService.findUserByOpenId(aouAuthInfo.getOpenId(),false);
			model.addAttribute("openID",aouAuthInfo.getOpenId());
			Map<String, Object> searchParams = new HashMap<String,Object>();
			Results results = sysProjectService.searchDtosByPage(searchParams,1,1000);
			
			model.addAttribute("res",results);
						
			List<Item> items = new ArrayList<Item>();
			if(results.getData()!=null){
				List<Project> list = (List<Project>)((Map)results.getData()).get("rows");
				if(list!=null && list.size()>0){
					for(int i = 0;i<list.size();i++){
						Project pro = list.get(i);
						Item item = new Item(pro.getProId()+"",pro.getName());
						items.add(item);
					}
				}
			}
			model.addAttribute("projects",new JacksonUtil().getJson(items));
			if(currentUser==null){
				return "/wx/user/register";
			}else if(currentUser.getStatus()==UserUtil.APPROVE_NO){
				model.addAttribute("msg", "注册成功,等待审批");
				return "/wx/user/approve";
			}else if(currentUser.getIsAvailable()==UserUtil.DISABLE_YES){
				model.addAttribute("msg", "账号已禁用,请联系管理员");
				return "/wx/message";
			}else{
				model.addAttribute("msg", "注册成功");
				return "/wx/user/success";
			}
		}catch(Exception e){
			return "/wx/user/register";
		}
	}*/
	
	@RequestMapping(value = "/saveStudent",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public String save(@RequestBody TTudentInfo info,RedirectAttributes attrs ) {
		Results results = null;
		if(info.getOpenId()!=null && StringUtil.isNotEmpty(info.getOpenId())){
			TTudentInfo tti =  sTudentService.findbyOpenId(info.getOpenId());
			if(tti!=null){
				results = new Results(API_RETURN_STATUS.USEREXIST_ERROR.value(), "该用户已注册！");
			}else{
				info.setStatus(1);
				info.setAvailable(1);
				info.setCreateTime(new Date());
				sTudentService.save(info);
				results = new Results(API_RETURN_STATUS.NORMAL.value(), "保存成功！");
			}
		}else{
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), "OpenID必填！");
		}
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/updateStudent",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public String updateStudent(@RequestBody TTudentInfo info,RedirectAttributes attrs ) {
		Results results = null;
		if(info.getOpenId()!=null && StringUtil.isNotEmpty(info.getOpenId())){
			TTudentInfo tti =  sTudentService.findbyOpenId(info.getOpenId());
			if(tti==null){
				results = new Results(API_RETURN_STATUS.USERNOEXIST_ERROR.value(), "该用户不存在！");
			}else{
				info.setId(tti.getId());
				info.setStatus(1);
				info.setAvailable(1);
				info.setUpdateTime(new Date());
				sTudentService.updateStudent(info);
				results = new Results(API_RETURN_STATUS.NORMAL.value(), "修改成功！");
			}
		}else{
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), "OpenID必填！");
		}
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/findStudentByOpenId/{openId}",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String findStudentByOpenId(@PathVariable ("openId")String openId,RedirectAttributes attrs ) {
		Results results = null;
		if( StringUtil.isNotEmpty(openId)){
			TTudentInfo tti =  sTudentService.findbyOpenId(openId);
			if(tti!=null){
				results = new Results(API_RETURN_STATUS.NORMAL.value(), "查询成功！");
				results.setData(tti);
			}else{
				results = new Results(API_RETURN_STATUS.USERNOEXIST_ERROR.value(), "该用户不存在！");
			}
		}else{
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), "OpenID必填！");
		}
		return JSON.toJSONString(results);
	}
	

	/*@RequestMapping(value = "/view")
	public String view(HttpServletRequest request,HttpServletResponse response,Model model) {
		OAuthInfo aouAuthInfo  = WeixinHelper.getUserOpenId(request);
		User user  = sysUserService.findUserByOpenId(aouAuthInfo.getOpenId(),false);
		model.addAttribute("user",user);
		return "/wx/user/viewinfo";
	}*/
	
	
	@RequestMapping(value = "/listSchool",produces="application/json;charset=UTF-8")
	@ResponseBody 
	public String listSchool(HttpServletRequest request,HttpServletResponse response) {
		
		List<TSchoolInfo> list = tSchoolService.findAll();
		Results results = new Results(API_RETURN_STATUS.NORMAL.value(),"查询成功");
		results.setData(list);
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/listGrade",produces="application/json;charset=UTF-8")
	@ResponseBody 
	public String listGrade(HttpServletRequest request,HttpServletResponse response) {
		List<TGradeInfo> list = tGradeService.findAll();
		Results results = new Results(API_RETURN_STATUS.NORMAL.value(),"查询成功");
		results.setData(list);
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/listGradeBySchool",produces="application/json;charset=UTF-8")
	@ResponseBody 
	public String listGradeBySchool(HttpServletRequest request,HttpServletResponse response) {
		String  schoolId = "";
		if(request.getParameter("shcoolId")!=null){
			schoolId = request.getParameter("shcoolId");
		}else{
			schoolId = "-1";
		}
		List<TGradeInfo> list = tGradeService.findBySchoolId(Integer.valueOf(schoolId));
		Results results = new Results(API_RETURN_STATUS.NORMAL.value(),"查询成功");
		results.setData(list);
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/toupload")
	public String toupload(HttpServletRequest request,HttpServletResponse response) {
		return "/upload/uploadImg";
	}
	
	@RequestMapping(value="/imgUpload",produces="image/jpeg;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public String imgUpload(HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		//Map<String,Object> resultmap = new HashMap<String,Object>();
		
		// 创建一个通用的多部分解析器
		// 判断 request 是否有文件上传,即多部分请求
		String openId= request.getParameter("openId");
		
		if(StringUtil.isEmpty(openId)){
			Results results = new Results(API_RETURN_STATUS.PARA_ERROR.value(),"openID必填","");
			return new JacksonUtil().getJson(results);
		}
		
		TTudentInfo tti =  sTudentService.findbyOpenId(openId);
		if(tti==null){
			Results results = new Results(API_RETURN_STATUS.USERNOEXIST_ERROR.value(),"用户不存在","");
			return new JacksonUtil().getJson(results);
		}
		
		if (!multipartResolver.isMultipart(request)){
			Results results = new Results("99","文件读取失败","");
			return new JacksonUtil().getJson(results);
		}
			
		//转换成多部分request
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		//获得文件名： 
		Boolean bepicture = false;
		Iterator<String> iters = multiRequest.getFileNames();
		int i = 0;
		while (iters.hasNext()) {
			MultipartFile file = multiRequest.getFile(iters.next());
			if (file != null) {
				String filename = file.getOriginalFilename();
				String prefix=filename.substring(filename.lastIndexOf(".")+1);
				if(prefix.equalsIgnoreCase("gif") || prefix.equalsIgnoreCase("jpg")
					   ||prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("png")){
					bepicture = true;
				}
			}	
		}
		
		if(bepicture){
		    // 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				String path = ResourceLocator.getResourceAbsoluteLocation(ResourceLocator.TEMPLATEIMAGE)
					.getAbsolutePath() + File.separator + openId +File.separator;
				String returnpath = ResourceLocator.TEMPLATEIMAGE + File.separator + openId +File.separator;
				File f = new File(path);
				//判断父目录路径是否存在，即test.txt前的I:\a\b\
				if (!f.exists()) {    
				    try {
				    	//不存在则创建父目录
				        f.mkdirs();    
				        f.createNewFile();
				    } catch (IOException e) {
				        e.printStackTrace();
				    }
				}
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String myFileName = file.getOriginalFilename();
					if (StringUtils.isNotBlank(myFileName.trim())) {
						String[] sp = myFileName.split("\\.");
						String suffix = DateUtil.transfromDateToString("yyyyMMddHHmm", new Date());
						String fileName = suffix + "." + sp[sp.length - 1];
						// 定义上传路径
						String filePath = path + fileName;
						File localFile = new File(filePath);
						file.transferTo(localFile);
						/*resultmap.put("status", "0");
						resultmap.put("message", "上传成功");
						resultmap.put("fileName", fileName);
						resultmap.put("filePath", filePath);*/
						Map<String,Object> resultmap = new HashMap<String,Object>();
						resultmap.put("fileName", fileName);
						resultmap.put("filePath", returnpath+fileName);
						Results results = new Results(API_RETURN_STATUS.NORMAL.value(),"上传成功",resultmap);
						return new JacksonUtil().getJson(results);
					}
				}
			}
		}else{
			Results results = new Results("98","文件格式错误","");
			return new JacksonUtil().getJson(results);
		}
		
		return null;
			
	}
	
	
	@RequestMapping(value="/uploadQuestions",produces="image/jpeg;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public String uploadQuestions(HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		//Map<String,Object> resultmap = new HashMap<String,Object>();
		
		// 创建一个通用的多部分解析器
		// 判断 request 是否有文件上传,即多部分请求
		String fileName = "";
		String openId= request.getParameter("openId");
		String urlpath = ResourceLocator.TEMPLATEIMAGE + File.separator + openId +File.separator;
		String subjectId= request.getParameter("subjectId");
		String title= request.getParameter("title");
		if(StringUtil.isEmpty(openId)){
			Results results = new Results(API_RETURN_STATUS.PARA_ERROR.value(),"openID必填","");
			return new JacksonUtil().getJson(results);
		}
		TTudentInfo tti =  sTudentService.findbyOpenId(openId);
		if(tti==null){
			Results results = new Results(API_RETURN_STATUS.USERNOEXIST_ERROR.value(),"用户不存在","");
			return new JacksonUtil().getJson(results);
		}
		if (!multipartResolver.isMultipart(request)){
			Results results = new Results("99","文件读取失败","");
			return new JacksonUtil().getJson(results);
		}
			
		//转换成多部分request
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		//获得文件名： 
		Boolean bepicture = false;
		Iterator<String> iters = multiRequest.getFileNames();
		int i = 0;
		while (iters.hasNext()) {
			System.out.println("========iters======="+(i++));

			MultipartFile file = multiRequest.getFile(iters.next());
			if (file != null) {
				String filename = file.getOriginalFilename();
				String prefix=filename.substring(filename.lastIndexOf(".")+1);
				if(prefix.equalsIgnoreCase("gif") || prefix.equalsIgnoreCase("jpg")
					   ||prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("png")){
					bepicture = true;
				}
			}	
		}
		
		TTudentInfo student = sTudentService.findbyOpenId(openId);
		
		if(bepicture){
		    // 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				String path = ResourceLocator.getResourceAbsoluteLocation(ResourceLocator.TEMPLATEIMAGE)
					.getAbsolutePath() + File.separator + openId +File.separator;
				File f = new File(path);
				//判断父目录路径是否存在，即test.txt前的I:\a\b\
				if (!f.exists()) {    
				    try {
				    	//不存在则创建父目录
				        f.mkdirs();    
				        f.createNewFile();
				    } catch (IOException e) {
				        e.printStackTrace();
				    }
				}
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String myFileName = file.getOriginalFilename();
					if (StringUtils.isNotBlank(myFileName.trim())) {
						String[] sp = myFileName.split("\\.");
						String suffix = DateUtil.transfromDateToString("yyyyMMddHHmm", new Date());
						suffix = student.getPhone()+"_"+suffix;
						fileName = suffix + "." + sp[sp.length - 1];
						// 定义上传路径
						String filePath = path + fileName;
						File localFile = new File(filePath);
						file.transferTo(localFile);
					}
				}
				
				if(fileName.length()>0){
					System.out.println(tti.getClassId()+"==classid==="+tti.getGradeId()+"==schoolid=="+tti.getSchoolId());
					String filePath = urlpath+fileName;
					System.out.println("==filePath==="+filePath);

					TQuestionsInfo tq = new TQuestionsInfo();
					tq.setTitle(title);
					tq.setStudentId(tti.getId());
					tq.setSchoolId(tti.getSchoolId());
					tq.setGradeId(tti.getGradeId());
					tq.setClassId(tti.getClassId());
					tq.setSubjectId(Integer.parseInt(subjectId));
					tq.setCreateTime(new Date());
					tq.setUrl(filePath.replaceAll("\\\\", "/"));
					tq.setStatus(1);
					tQuestionsService.save(tq);
				}
			}
			Map<String,Object> resultmap = new HashMap<String,Object>();
			Results results = new Results(API_RETURN_STATUS.NORMAL.value(),"保存成功",resultmap);
			return new JacksonUtil().getJson(results);
		}else{
			Results results = new Results("98","文件格式错误","");
			return new JacksonUtil().getJson(results);
		}
		/*if(fileName.length()>0){
			System.out.println(tti.getClassId()+"==classid==="+tti.getGradeId()+"==schoolid=="+tti.getSchoolId());
			String filePath = urlpath+fileName;
			TQuestionsInfo tq = new TQuestionsInfo();
			tq.setTitle(title);
			tq.setStudentId(tti.getId());
			tq.setSchoolId(tti.getSchoolId());
			tq.setGradeId(tti.getGradeId());
			tq.setClassId(tti.getClassId());
			tq.setSubjectId(Integer.parseInt(subjectId));
			tq.setCreateTime(new Date());
			tq.setUrl(filePath.replaceAll("\\\\", "/"));
			tq.setStatus(1);
			tQuestionsService.save(tq);
			Map<String,Object> resultmap = new HashMap<String,Object>();
			Results results = new Results(API_RETURN_STATUS.NORMAL.value(),"保存成功",resultmap);
			return new JacksonUtil().getJson(results);
		}*/
		//return null;
	}
		
	
}
